package com.gsmr.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.gsmr.entity.Balise_info;
import com.gsmr.entity.PageBean;
import com.gsmr.service.Balise_infoService;
import com.gsmr.util.ExcelUtil;
import com.gsmr.util.FormatDate;
import com.gsmr.util.PropertityUtil;
import com.gsmr.util.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


@Controller
@RequestMapping("/balise_info")
public class Balise_infoController {

	@Resource
	private Balise_infoService balise_infoService;

	/**
	 * 分页条件查询Balise_info
	 */
	@RequestMapping("/list")
	public void list(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows, Balise_info s_balise_info, HttpServletResponse response)
			throws Exception {
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<Balise_info> balise_infoList = balise_infoService.find(map);
		Long total = balise_infoService.getTotal(map);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(balise_infoList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
	}


	/**
	 * 添加或者修Balise_info
	 * 
	 * @param balise_info
	 * @param response
	 * @param flag
	 *            1 添加 2修改
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public void save(Balise_info balise_info, HttpServletResponse response, Integer flag) throws Exception {
		int resultTotal = 0; // 操作的记录条数
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("BaliseId", balise_info.getBaliseId());
		map.put("NID_LRBG", balise_info.getNID_LRBG());
		map.put("Kilometer", balise_info.getKilometer());
		map.put("Balise_Name", balise_info.getBalise_Name());
		if (flag == 1) {
			resultTotal = balise_infoService.add(map);
		} else {
			resultTotal = balise_infoService.update(map);
		}
		JSONObject result = new JSONObject();
		if (resultTotal > 0) {
			result.put("success", true);
		} else {
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
	}

	/**
	 * 删除Balise_info
	 */
	@RequestMapping("/delete")
	public void delete(@RequestParam(value = "baliseIds") String ids, HttpServletResponse response) throws Exception {
		String[] idsStr = ids.split(",");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		for (int i = 0; i < idsStr.length; i++) {
			map.put("BaliseId", idsStr[i]);
			balise_infoService.delete(map);
		}
		JSONObject result = new JSONObject();
		result.put("success", true);
		ResponseUtil.write(response, result);
	}


	/**
	 * 导出Balise_info
	 */
	@RequestMapping("/export")
	public void export(@RequestParam(value = "baliseIds") String ids, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<>();
		Workbook wb = new HSSFWorkbook();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		String headers[] = { "BaliseId", "NID_LRBG", "Kilometer", "Balise_Name"};
		if (ids != null && !ids.equals("null") && !ids.equals("")) {
			List<String> idsList = Arrays.asList(ids.split(","));
			map.put("BaliseIds", idsList);
			List<Balise_info> balise_infoList = balise_infoService.findByBaliseIds(map);
			try {
				ExcelUtil.fillExcelData_Balise_info(balise_infoList, wb, headers);
				ResponseUtil.export(response, wb, "导出Balise_info" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			map.put("BaliseIds", null);
			List<Balise_info> balise_infoList = balise_infoService.findByBaliseIds(map);
			try {
				ExcelUtil.fillExcelData_Balise_info(balise_infoList, wb, headers);
				ResponseUtil.export(response, wb, "导出Balise_info" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 用模板导出Balise_info
	 */
	@RequestMapping("/exportByTemplate")
	public void exportByTemplate(@RequestParam(value = "baliseIds") String ids, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		if (ids != null && !ids.equals("null") && !ids.equals("")) {
			List<String> idsList = Arrays.asList(ids.split(","));
			map.put("BaliseIds", idsList);
			List<Balise_info> balise_infoList = balise_infoService.findByBaliseIds(map);
			try {
				Workbook wb = ExcelUtil.fillExcelDataWithTemplate_Balise_info(balise_infoList, "balise_infoExportTemplate.xls");
				ResponseUtil.export(response, wb, "利用模版导出excel" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			map.put("BaliseIds", null);
			List<Balise_info> balise_infoList = balise_infoService.findByBaliseIds(map);
			try {
				Workbook wb = ExcelUtil.fillExcelDataWithTemplate_Balise_info(balise_infoList, "balise_infoExportTemplate.xls");
				ResponseUtil.export(response, wb, "利用模版导出excel" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Balise_info上传
	 */
	@RequestMapping("/upload")
	public void upload(HttpServletRequest request, HttpServletResponse response, Integer uploadFlag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("BaliseId", "0 OR 1=1");
		if (uploadFlag == 2) {
			int flag = balise_infoService.delete(map);
		}
		
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();

			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					//String path = file.getOriginalFilename();
					String path = "已导入" + new Date().getTime() + file.getOriginalFilename();
					// 上传
					File newFile = new File(path);
					file.transferTo(newFile);
					// 写数据进数据库
					POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(newFile));
					newFile.delete();
					HSSFWorkbook wb = new HSSFWorkbook(fs);
					HSSFSheet hssfSheet = wb.getSheetAt(0); // 获取第一个Sheet页
					JSONObject result = new JSONObject();
					try {
						if (hssfSheet != null) {
							for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
								HSSFRow hssfRow = hssfSheet.getRow(rowNum);
								if (hssfRow == null) {
									continue;
								}
								String  id = ExcelUtil.formatCell(hssfRow.getCell(0));
								if (id.length() < 1 || existBaliseId(id, null)) {
									continue;
								}
								map.put("BaliseId", ExcelUtil.getIntegerPart(id));
								map.put("NID_LRBG", ExcelUtil.getIntegerPart(ExcelUtil.formatCell(hssfRow.getCell(1))));
								map.put("Kilometer", ExcelUtil.getIntegerPart(ExcelUtil.formatCell(hssfRow.getCell(2))));
//								map.put("Balise_Name", ExcelUtil.getIntegerPart(ExcelUtil.formatCell(hssfRow.getCell(3))));
								map.put("Balise_Name", ExcelUtil.formatCell(hssfRow.getCell(3)));
								balise_infoService.add(map);
							}
						}
						result.put("success", true);
					} catch (Exception e) {
						result.put("success", false);
						e.printStackTrace();
					}
					ResponseUtil.write(response, result);
				}
			}
		}
	}

	
	/**
	 * 判断是否存在指定用户名
	 */
	@RequestMapping("/existBaliseId")
	public Boolean existBaliseId(String BaliseId, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("BaliseId", BaliseId);
		
		boolean hasDuplicate = false;
		
		if (balise_infoService.findByBaliseId(map) == null) {
			result.put("exist", false);
		} else {
			result.put("exist", true);
			hasDuplicate = true;
		}
		if (response != null) {
			ResponseUtil.write(response, result);
			return null;
		}
		return hasDuplicate;
	}
}